<template>
    <!-- 标签栏 -->
    <van-tabs v-model:active="StatusActive" sticky @click-tab="OnTabChange" :background="'#fff'" color="#fba12f" title-active-color="#fba12f" background="#f7f7f7">
        <van-tab v-for="(item, key) in StatusList" :title="item.title" :name="item.value" :key="key"></van-tab>
    </van-tabs>

    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="refreshing" @refresh="OnRefresh">
        <!-- 加载列表 -->
        <van-list
            v-model:loading="loading"
            :finished="finished"
            :offset="10"
            finished-text="没有更多了"
            @load="OnLoad"
        >
            <div class="list">
                <!-- 商品卡片 -->
                <div class="item" v-for="item in list" :key="item.id">

                    <div class="header">
                        <div class="code">订单号：{{ item.code }}</div>
                        <div class="status">{{ item.status_text }}</div>
                    </div>

                    <van-card
                        :thumb="item.product.products.thumb_text"
                        @click="OnOpenProductCard(item.order_product)"
                    >
                        <template #title>
                            <div class="title">{{ item.product.products.name }}</div>
                        </template>

                        <!-- 卡片的插槽部分 -->
                        <template #desc v-if="item.product.attrs">
                            <van-tag v-for="(attr,index) in JSON.parse(item.product.attrs)" :key="index" class="tag" type="primary">{{attr.value}}</van-tag>
                        </template>

                        <!-- 卡片的插槽部分 -->
                        <template #desc v-else>
                            <van-tag class="tag" type="danger">无商品规格</van-tag>
                        </template>

                        <template #price>
                            <div class="price-box">
                                <div class="price">商品总价：￥ {{ item.product.total }}</div>
                                <div class="num">x{{ item.product.pronum }}</div>
                            </div>
                        </template>
                    </van-card>

                    <div class="footer">

                        <div class="box">

                            <div class="time">
                                下单时间：{{ item.createtime_text }}
                            </div>

                            <div class="total">
                                <div class="coupon" v-if="item.coupon">优惠：￥ {{ item.coupon_price }}</div>
                                <div>实付款：￥ {{ item.amount }}</div>
                            </div>
                        </div>

                        <div class="btn-list">
                            <!-- status = 1 仅退款 -->
                            <van-button v-if="item.status == '1'" class="button" type="danger" size="mini" @click="OnRefund1(item.id)">申请退款</van-button>
                            <van-button v-if="item.status == '2'" class="button" type="danger" size="mini" @click="OnRefund2(item.id)">申请退货退款</van-button>

                            <!-- status = 2 -->
                            <van-button v-if="item.status == '2'" class="button" type="success" size="mini" @click="OnConfirmReceive(item.id)">确认收货</van-button>
                            <van-button v-if="item.status == '2'" class="button" type="warning" size="mini" @click="ToExpress(item.id)">物流详情</van-button>

                            <!-- status = 3 已收货 -->
                            <van-button v-if="item.status == '3'" class="button" type="warning" size="mini" @click="ToOrderInfo(item.id)">立即评价</van-button>

                            <!-- 退货退款 -->
                            <van-button v-if="item.status == '-2'" class="button" type="success" size="mini">等待后台审核...</van-button>
                            <van-button v-if="item.status == '-3'" class="button" type="warning" size="mini" @click="OnBackInfo(item)">请填写退货信息</van-button>

                            <!-- 退货失败 -->
                            <van-button v-if="item.status == '-5'" class="button" type="danger" size="mini" @click="OnRefundInfo(item)">后台拒绝退货原因</van-button>

                            <van-button class="button" type="primary" size="mini" @click="ToOrderInfo(item.id)">订单详情</van-button>
                        </div>
                     </div>
                </div>
            </div>
        </van-list>
    </van-pull-refresh>

    <!-- 商品列表弹出框 -->
    <van-popup 
        v-model:show="ProductShow" 
        position="bottom" 
        round
        style="padding: 10px 0;"
    >
        <van-card v-for="item in ProductList" :thumb="item.products.thumb_text" :num="item.pronum">
            <template #title>
                <div class="title">{{item.products.name}}</div>
            </template>
    
            <!-- 卡片的插槽部分 -->
            <template #desc v-if="item.attrs">
                <van-tag v-for="(attr,index) in JSON.parse(item.attrs)" :key="index" class="tag" type="primary">{{attr.value}}</van-tag>
            </template>

            <template #desc v-else>
                <van-tag class="tag" type="danger">无规格数据</van-tag>
            </template>
    
            <template #tags>
                <div class="price">单价：￥{{item.price}}</div>
            </template>
    
            <template #price>
                <div class="price">合计：￥{{item.total}}</div>
            </template>
        </van-card>

        <div style="width:80%;margin:1em auto 0em;">
            <van-button round block type="primary" @click="ProductShow = false">关闭</van-button>
        </div>
    </van-popup>

    <!-- 仅退款弹框 -->
    <van-popup v-model:show="ApplyShow1" position="bottom" round :style="{paddingBottom: '20px'}">
        <van-picker
            title="退款原因"
            :columns="RemarkList"
            @cancel="ApplyShow1 = false"
            @confirm="OnRefundApply"
        />
    </van-popup>
</template>

<script setup>
const { proxy } = getCurrentInstance();

// 从状态管理获取用户信息
const business = proxy.$business;

// 标签栏的变量
const StatusActive = ref('all');
const StatusList = ref([
    { title: '全部', value: 'all' },
    { title: '已支付', value: '1' },
    { title: '已发货', value: '2' },
    { title: '已收货', value: '3' },
    { title: '已完成', value: '4' },
    { title: '退货退款', value: '-1' },
]);

// 列表变量
const refreshing = ref(false);
const finished = ref(false);
const loading = ref(false);
const list = ref([]);
const page = ref(1);

// 商品列表相关的变量
const ProductShow = ref(false);
const ProductList = ref([]);

// 申请仅退款
const orderid = ref(0);
const ApplyShow1 = ref(false);
const RemarkList = ref([
    {text: '拍错了', value: '拍错了'},
    {text: '地址有误', value: '地址有误'},
    {text: '不想要了', value: '不想要了'},
    {text: '参数选错了', value: '参数选错了'},
    {text: '选择其他的', value: '选择其他的'},
]);

// 下拉刷新函数
const OnRefresh = () =>
{
    refreshing.value = true;
    finished.value = false;
    loading.value = true;
    list.value = [];
    page.value = 1;

    setTimeout(OnLoad,1500);
}

// 上拉加载函数
const OnLoad = async () =>
{
    // 如果当前通过下拉刷新触发上拉加载，需要手动停止下拉刷新
    if(refreshing.value === true) refreshing.value = false;

    // 组装请求参数
    const params = {
        page:page.value,
        busid:business.value.id,
        status:StatusActive.value,
    }

    const result = await proxy.$http.post({
        url:'/order/index',
        params
    });

    loading.value = false;

    if(result.code === 1)
    {
        // 合并数组
        list.value = list.value.concat(result.data.list);
        let count = result.data.count;

        list.value.map(item =>
        {
            item.product = item.order_product[0] ?? {};

            // 如果有使用优惠券
            if(item.coupon)
            {
                // 购买的商品总价
                let amount = 0;

                // 循环计算
                item.order_product.map(product => {
                    amount += parseFloat(product.total);
                })

                // 优惠价格
                item.coupon_price = (amount - parseFloat(item.amount)).toFixed(2);
            }
        });

        // 如果没有更多数据了，就说明已经加载到底了
        if(list.value.length === count)
        {
            finished.value = true;

            return false;
        }

        page.value = page.value + 1;
    }else{
        finished.value = true;

        proxy.$fail(result.msg);
    }
}

// 打开商品列表，显示所有商品
const OnOpenProductCard = (list) =>
{
    // 显示弹出层
    ProductShow.value = true;

    ProductList.value = list;
}

// 去订单详情
const ToOrderInfo = (orderid) => proxy.$router.push({path:'/order/info',query:{orderid}});

// 申请仅退款
const OnRefund1 = (id) =>
{
    proxy.$confirm({
        title: '申请退款',
        message: '是否确认申请该订单退款?'
    }).then(async () => {
        ApplyShow1.value = true;
        orderid.value = id;
    }).catch(err => {});
}

// 选择了退款原因的确认事件
const OnRefundApply = async ({selectedOptions}) =>
{
    const refundreason = selectedOptions[0].value ?? '拍错了';

    // 组装参数
    const params = {
        orderid:orderid.value,
        busid:business.value.id,
        refundreason
    }

    const result = await proxy.$http.post({
        url:'/order/refund',
        params
    });

    if(result.code === 1)
    {
        ApplyShow1.value = false;

        proxy.$success(result.msg,() =>
        {
            OnRefresh();
        });
    }else{
        proxy.$fail(result.msg);
    }
}

// 确认收货
const OnConfirmReceive = (id) =>
{
    proxy.$confirm({
        title:'确认收货',
        message:'是否确认收货？'
    }).then(async () => {
        // 组装请求参数
        const params = {
            busid:business.value.id,
            orderid:id
        }

        // 发起请求
        const result = await proxy.$http.post({
            url:'/order/receive',
            params
        });

        if(result.code === 1)
        {
            proxy.$success(result.msg,() =>
            {
                OnRefresh();
            });
        }else{
            proxy.$fail(result.msg);
        }
    }).catch((err) => {});
}

// 切换tab栏事件
const OnTabChange = () =>
{
    // 直接调用下拉刷新函数
    OnRefresh();
}

// 跳转物流详情
const ToExpress = (id) => proxy.$router.push({path:'/order/express',query:{orderid:id}});
</script>

<style scoped>
@import url('/assets/css/OrderIndex.css');
</style>